package com.vitabuybuy.tv.ui.auth

import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.os.CountDownTimer
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.base.appContext
import com.library.common.ext.logE
import com.library.common.ext.mmkv
import com.library.common.ext.setOnclickNoRepeat
import com.library.common.net.HeadInterceptor
import com.library.common.toast.XToast
import com.library.common.util.MMKVContancts
import com.tencent.qcloud.tim.uikit.TUIKit
import com.tencent.qcloud.tim.uikit.TUIKitImpl
import com.vitabuybuy.tv.BuildConfig
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityPhoneLoginBinding
import com.vitabuybuy.tv.dialog.AreaCodePopup
import com.vitabuybuy.tv.ui.MainActivity
import com.vitabuybuy.tv.ui.auth.viewmodel.AuthViewModel
import com.vitabuybuy.tv.ui.tencent.liveroom.IMLVBLiveRoomListener
import com.vitabuybuy.tv.ui.tencent.liveroom.MLVBLiveRoom
import com.vitabuybuy.tv.ui.tencent.liveroom.roomutil.commondef.LoginInfo
import com.vitabuybuy.tv.utils.StringUtil
import kotlinx.android.synthetic.main.activity_phone_login.*

class PhoneLoginActivity : BaseActivity<AuthViewModel, ActivityPhoneLoginBinding>() {

    private var isGetCode = false

    override val isUseBaseTitleBar: Boolean
        get() = true
    override val layoutId: Int
        get() = R.layout.activity_phone_login
    private var defaultAreaCode = "86"
    private var logType = 1

    override fun initView(savedInstanceState: Bundle?) {
        setTitle(getString(R.string.login))
        etPhone.setText("15521282298")
        etPassword.setText("123456")
    }

    override fun observeData() {
        viewModel.tokenInfo.observe(this, Observer {
            HeadInterceptor.sessionId = it.token
            mmkv.encode(MMKVContancts.USER_PHONE, it.phone.split("-")[1])
            mmkv.encode(MMKVContancts.SESSIONID, it.token)
            mmkv.encode(MMKVContancts.IS_LOGIN_IN, true)
            viewModel.getUserInfo()
        })
        viewModel.userInfoDto.observe(this, Observer {
            val loginInfo = LoginInfo().apply {
                sdkAppID = BuildConfig.LIVEAPPID.toLong()
                userID = it.id.toString()
                userSig = it.userSign
                userName = it.nickname
                userAvatar = it.avatar
            }
            MLVBLiveRoom.sharedInstance(appContext)
                .login(loginInfo, object : IMLVBLiveRoomListener.LoginCallback {
                    override fun onSuccess() {
                        btnLogin.setBtnEnable(true)
                        mmkv.encode(MMKVContancts.USER_EMAIL, it.email)
                        mmkv.encode(MMKVContancts.USER_ID, it.id)
                        mmkv.encode(MMKVContancts.USER_SIGN, it.userSign)
                        mmkv.encode(MMKVContancts.USER_AVATAR, it.avatar)
                        mmkv.encode(MMKVContancts.USER_NICKNAME, it.nickname)
                        MainActivity.openActivity(mContext)
                    }

                    override fun onError(errCode: Int, errInfo: String?) {
                        btnLogin.setBtnEnable(true)
                        errInfo?.run {
                            errCode.logE("JIA--errCode--")
                            this.logE("JIA--errInfo--")
                            XToast.error("直播登录失败，请联系管理员")
                        }
                    }
                })
        })
    }

    override fun eventHandling() {
        setOnclickNoRepeat(
            tvPwdLogin, tvSmsLogin, tvForgetPassword,
            ivEye, tvGetSmsCode, btnLogin, countryCodePicker
        ) { v ->
            when (v) {
                tvPwdLogin -> {
                    logType = 1
                    rlSmsCode.visibility = View.GONE
                    rlPassword.visibility = View.VISIBLE
                    tvPwdLogin.setTextColor(Color.parseColor("#151F33"))
                    tvSmsLogin.setTextColor(Color.parseColor("#A8ABB3"))
                    tvPwdLogin.typeface = Typeface.DEFAULT_BOLD
                    tvSmsLogin.typeface = Typeface.DEFAULT
                    tvPwdLogin.textSize = 16f
                    tvSmsLogin.textSize = 14f
                    tvForgetPassword.visibility = View.VISIBLE
                }
                tvSmsLogin -> {
                    logType = 0
                    rlPassword.visibility = View.GONE
                    rlSmsCode.visibility = View.VISIBLE
                    tvSmsLogin.setTextColor(Color.parseColor("#151F33"))
                    tvPwdLogin.setTextColor(Color.parseColor("#A8ABB3"))
                    tvSmsLogin.typeface = Typeface.DEFAULT_BOLD
                    tvPwdLogin.typeface = Typeface.DEFAULT
                    tvSmsLogin.textSize = 16f
                    tvPwdLogin.textSize = 14f
                    tvForgetPassword.visibility = View.INVISIBLE
                }
                ivEye -> {
                    if (etPassword.transformationMethod == HideReturnsTransformationMethod.getInstance()) {
                        etPassword.transformationMethod = PasswordTransformationMethod.getInstance()
                        ivEye.setImageResource(R.drawable.icon_login_eyes_n)
                    } else {
                        etPassword.transformationMethod =
                            HideReturnsTransformationMethod.getInstance()
                        ivEye.setImageResource(R.drawable.icon_login_eyes)
                    }
                }
                tvGetSmsCode -> {
                    if (etPhone.text.isEmpty()) {
                        XToast.normal(getString(R.string.enter_phone_number))
                        return@setOnclickNoRepeat
                    }
//                if (!RegexUtils.isMobileExact(etPhone.text)) {
//                    XToast.normal(getString(R.string.enter_correct_phone_number))
//                    return
//                }
                    if (tvSmsLogin.isVisible) {
                        viewModel.sendToPhone2(
                            etPhone.text.toString(),
                            defaultAreaCode
                        )
                    } else {
                        viewModel.sendToPhone(
                            "",
                            etPhone.text.toString(),
                            defaultAreaCode
                        )
                    }
                }
                btnLogin -> {
                    if (etPhone.text.isEmpty()) {
                        XToast.normal(getString(R.string.enter_phone_number))
                        return@setOnclickNoRepeat
                    }
//                if (!RegexUtils.isMobileExact(etPhone.text)) {
//                    XToast.normal(getString(R.string.enter_correct_phone_number))
//                    return
//                }
                    if (logType == 1) {
                        if (etPassword.text.isEmpty()) {
                            XToast.normal(getString(R.string.enter_password))
                            return@setOnclickNoRepeat
                        }
                        if (!StringUtil.judgePassword(etPassword.text.toString())) {
                            XToast.normal(getString(R.string.password_dialog_tip))
                            return@setOnclickNoRepeat
                        }
                        btnLogin.setBtnEnable(false)
                        viewModel.loginByPhoneAndPwd(
                            etPhone.text.toString(),
                            etPassword.text.toString(),
                            defaultAreaCode
                        )
                    } else {
                        if (!isGetCode) {
                            XToast.normal(getString(R.string.please_get_code))
                            return@setOnclickNoRepeat
                        }
                        if (etSmsCode.text.isEmpty()) {
                            XToast.normal(getString(R.string.enter_code))
                            return@setOnclickNoRepeat
                        }
                        btnLogin.setBtnEnable(false)
                        viewModel.loginByPhoneAndCode(
                            etPhone.text.toString(),
                            etSmsCode.text.toString(),
                            defaultAreaCode
                        )
                    }
                }
                tvForgetPassword -> {
                    FindPasswordActivity.openActivity(mContext, FindPasswordActivity.FORGET_PWD)
                }
                countryCodePicker -> {
                    AreaCodePopup(this) {
                        countryCodePicker.text = it
                        defaultAreaCode = it.replace("+", "")
                    }.showPopupWindow()
                }
            }
        }
    }


    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            1 -> {
                XToast.success(getString(R.string.already_sms_code))
                timer.start()
            }
            -100->{
                btnLogin.setBtnEnable(true)
            }
        }
    }

    private val timer = object : CountDownTimer((60 * 1000).toLong(), 1000) {
        override fun onTick(millisUntilFinished: Long) {
            isGetCode = true
            mBinding.tvGetSmsCode.text = String.format(
                getString(R.string.get_sms_code_s),
                millisUntilFinished / 1000
            )
            mBinding.tvGetSmsCode.isEnabled = false
        }

        override fun onFinish() {
            mBinding.tvGetSmsCode.text = getString(R.string.get_sms_code)
            mBinding.tvGetSmsCode.isEnabled = true
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        timer.cancel()
    }

    companion object {
        fun openActivity(mContext: BaseActivity<*, *>) {
            mContext.startActivity(null, PhoneLoginActivity::class.java)
        }
    }
}
